package main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import Utils.Utils;

import ranks.Rank;


public class User extends Thread {
   
   private BufferedReader in;
   private PrintWriter out;
   private Room room;
   private String inLine;
   public String name;
   private Rank rank;
   
   public User(Socket socket, Room room) throws IOException {
      super("User");
      this.room = room;
      
      out = new PrintWriter(socket.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
   }
   
   /**
    * Dispatches a message to the client
    */
   public void dispatch(String msg) {
      out.println(msg);
   }

   @Override
   public void run() {
      try {
         while ((inLine = in.readLine()) != null) {
            if (name == null) {
               name = inLine;
               this.rank = Utils.getIPRank(this);
               room.dispatchRoomMsg(Messages.hasConnected(name));
            } else {
               if (!room.getPlugins().call(inLine, room, this)) {
                  room.dispatchChatMsg(this, inLine);
               }
            }
         }
      } catch (IOException e) {
         //TODO: fix catching
         System.out.println(e.getMessage());
         close();
         room.removeUser(this);
         room.dispatchRoomMsg(Messages.hasDisconnected(name));
      }
   }
   
   public void close() {
      try {
         in.close();
         out.close();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      room.removeUser(this);
   }
   
   public void jump(Room room) {
   	this.room.removeUser(this);
   	this.room = room;
   	room.addUser(this);
   }

   public Room getRoom() {
      return room;
   }

   public Rank getRank() {
      return rank;
   }

   public void setRank(Rank rank) {
      this.rank = rank;
   }

}
